import { ElMessage } from 'element-plus'
import Chatmessage from './chatmessage/ChatMessage.vue';
import { BASE_URL } from '@/utils/zongID';
import DOMPurify from 'dompurify';
// import marked from 'marked';  // 替换为markdown-it
import MarkdownIt from 'markdown-it';
import { ChatDotSquare,Comment } from '@element-plus/icons-vue'
export default {
    name: 'QueryInput',
    components: {
        Chatmessage,
        Comment
    },
    props: {
        exampleFileSelected: {
            type: Boolean,
            default: false
        },
        files: {
            type: Array,
            default: () => []
        },
        resMsg: {
            type: String,
            default: ''
        },
        id: {
            type: String,
            default: ''
        },
        isUploading: {
            type: Boolean,
            default: false
        }
    },
    emits: ['update:exampleFileSelected', 'example-file-change', 'update:resMsg',
        'update:id',
        'update:is-uploading'],
    data() {
        return {
            query: '',
            netSearchEnabled: true,
            mrakdownSearchEnabled: true,
            quickQuestions: [
                '分析这个表格',

            ],


            isSending: false,

            insight: '',
            questionsBuffer: '',
            questionsList: [],
            qaList: [],
            insightBuffer: '',
            currentQuestionIndex: 0,

            // 创建markdown-it实例
            md: null,
            egfiles: [],


        }
    },
    created() {
        // 初始化markdown-it
        this.md = new MarkdownIt();
    },
    methods: {
        downloadFile() {

        },
        async handleSubmit() {


            if (this.query.length === 0) {
                ElMessage.warning('请输入知识库相关问题');
                return;
            }
            if (this.files.length === 0) {
                ElMessage.warning('请选择文件');
                return;
            }
            if (this.resMsg === '') {
                ElMessage.warning('请先点击"处理上传文件"按钮进行文件处理');
                return;
            }
            if (this.isUploading) {
                ElMessage.warning("文件处理中，请稍等!");
                return;
            }
            this.resRaw = {};
            this.isSending = true;

            this.qaList = [];
            this.questionsList = [];
            this.questionsBuffer = '';
            this.insight = '';
            this.insightBuffer = '';
            this.currentQuestionIndex = 0;
            try {
                const response = await fetch(`${BASE_URL}/api/fuxigen-chat`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',

                        'Connection': 'keep-alive',
                        'Keep-Alive': 'timeout=3600, max=1000'
                    },
                    body: JSON.stringify({
                        question: this.query,
                        session_id: this.id,
                        generate_questions: true
                    }),
                });

                if (!response.ok || !response.body) {
                    throw new Error('Network response was not ok');
                }

                const reader = response.body.getReader();
                const decoder = new TextDecoder();
                let result = '';
                let isReading = true;
                while (isReading) {
                    const { done, value } = await reader.read();
                    if (done) {
                        isReading = false;
                        break;
                    }

                    const chunk = decoder.decode(value, { stream: true });
                    result += chunk;

                    const lines = result.split('\n');
                    result = lines.pop() || ''; // 保留最后一个不完整的行

                    for (const line of lines) {
                        if (line.trim() === '') continue; // 跳过空行
                        if (line.startsWith('data: ')) {
                            try {
                                const jsonStr = line.slice(6).trim(); // 移除 "data: " 前缀
                                const data = JSON.parse(jsonStr);
                                console.log("响应数据", data);

                                // 处理接收到的数据
                                // 1. 接收问题数据流，并保存到数组中
                                if (data.type === 'generated_questions') {
                                    // 追加新数据到缓冲区，去除可能存在的 ```json 和 ``` 标记
                                    const cleanContent = data.content.replace(/```json\s*|\s*```/g, '');
                                    this.questionsBuffer += cleanContent;
                                    console.log('清理后的问题数据:', this.questionsBuffer);

                                    try {
                                        // 尝试解析完整的 JSON
                                        const result = JSON.parse(this.questionsBuffer);
                                        console.log('问题列表解析结果:', result);
                                        if (result && result.问题) {
                                            // 成功解析到完整的问题列表
                                            this.questionsList = result.问题;
                                            console.log('解析出的问题列表:', this.questionsList);

                                            // 添加第一个问题到响应式数组
                                            this.qaList.push({
                                                question: this.questionsList[0],
                                                answer: { loading: true },
                                                loading: true
                                            });
                                            console.log(this.qaList);
                                            // 重置问题缓冲区
                                            this.questionsBuffer = '';
                                        }
                                    } catch (error) {
                                        console.log('数据不完整，继续等待...');
                                    }
                                }

                                // 2. 接收答案数据流，并保存到数组中
                                if (data.type === 'generated_answer') {
                                    const answer = this.processAnswer(data);

                                    // 更新当前问题的答案
                                    if (this.qaList[this.currentQuestionIndex]) {
                                        this.qaList[this.currentQuestionIndex].answer = answer;
                                    }

                                    // 准备下一个问题
                                    this.currentQuestionIndex++;
                                    if (this.currentQuestionIndex < this.questionsList.length) {
                                        this.qaList.push({
                                            question: this.questionsList[this.currentQuestionIndex],
                                            answer: { loading: true },
                                            loading: true
                                        });
                                        console.log("daaaaaaaaaaaaaaa", this.qaList);
                                    }
                                }

                                // 处理见解数据流
                                if (data.type === 'insight') {
                                    console.log("insight------------------1");
                                    // 追加新数据到缓冲区
                                    this.insightBuffer += data.content;

                                    // 按行分割内容
                                    const lines = this.insightBuffer ? this.insightBuffer.split('\n') : [];

                                    // 保留最后一行到缓冲区
                                    const lastLine = lines.pop();
                                    console.log("lastLine------------------", lastLine);
                                    // 切割去除lastline中可能存在的 undefined  示例：“这有助于更精准地制定运营策略。undefined”
                                    const cleanedLastLine = lastLine.replace(/undefined/g, '').trim();
                                    this.insightBuffer = typeof cleanedLastLine === 'string' ? cleanedLastLine : '';
                                    console.log("insight------------------2", this.insightBuffer);
                                    if (lines.length > 0) {

                                        // 处理完整的行
                                        const completeContent = lines.join('\n');




                                        try {


                                            // 使用markdown-it解析
                                            const parsedContent = DOMPurify.sanitize(
                                                this.md.render(completeContent),
                                                {
                                                    ADD_TAGS: ['p', 'div', 'pre', 'code', 'span', 'br'],
                                                    ADD_ATTR: ['class']
                                                }
                                            );



                                            this.insight += parsedContent;
                                            this.insightBuffer = '';
                                        } catch (e) {
                                            console.error('解析 insight 失败:', e);
                                        }
                                    }
                                }

                                // 处理最后一条数据
                                if (data.is_last && data.type === 'insight') {
                                    if (this.insightBuffer) {
                                        // 使用markdown-it解析
                                        const finalContent = DOMPurify.sanitize(this.md.render(this.insightBuffer), {
                                            ADD_TAGS: ['p', 'div', 'pre', 'code', 'span', 'br'],
                                            ADD_ATTR: ['class']
                                        });

                                        // 追加最后的内容
                                        this.insight += finalContent;
                                        this.insightBuffer = '';
                                    }
                                }




                                // this.resRaw = parsed;

                            } catch (e) {
                                console.warn('JSON 解析失败:', line);
                            }
                        }
                    }


                }
            } catch (error) {
                console.error('请求失败:', error);
                ElMessage.error('网络错误，请检查网络连接！');
            } finally {
                this.isSending = false;
            }
        },
        processAnswer(data) {
            const answer = {
                type: data.pandas_type,
                content: data.result,
                loading: false
            };

            switch (data.pandas_type) {
                case 'plot':
                    // Echarts 图表数据
                    answer.chartId = `chart-${this.currentQuestionIndex}`;
                    break;
                case 'dataframe':
                    // 表格数据
                    answer.tableData = data.result;
                    break;
                case 'number':
                    // 对象类型数据
                    answer.formattedContent = JSON.stringify(data.result, null, 2);
                    break;
                case 'string':
                    // 纯文本
                    answer.formattedContent = data.result;
                    break;
            }
            return answer;
        },
        async handleExampleFileChange(event) {
            const isChecked = event.target.checked;
            if (isChecked && this.files.length === 0) {
                // 如果勾选且文件选择框为空，则显示示例文件
                this.$emit('update:exampleFileSelected', true);
                     // 开始上传文件
                this.uploading = true;
                this.$emit('update:is-uploading', true);
                const response = await fetch('/商圈数据.csv');
                // const response = await fetch('/30种家庭常用解酒方法.txt');
                const blob = await response.blob();
                const file = new File([blob], '商圈数据.csv', {
                    // const file = new File([blob], '30种家庭常用解酒方法.txt》', {
                    type: 'application/pdf'
                });
                this.egfiles = [file];
                console.log(this.egfiles);
                const formData = new FormData();
                this.egfiles.forEach(file => {
                    formData.append('file', file);
                });
                try {
                    const response = await fetch(`${BASE_URL}/api/fuxigen-sessionid`, {
                        method: 'POST',
                        body: formData
                    });
                    if (response.ok) {
                        const res = await response.json();
                        this.$emit('update:resMsg', res.message);
                        this.$emit('update:id', res.id);
                        ElMessage.success('文件上传成功');
                    } else {
                        throw new Error('上传失败');
                    }
                } catch (error) {
                    console.error('上传文件时出错:', error);
                    ElMessage.error('上传文件失败，请重试');
                } finally {
                    this.uploading = false;
                    this.$emit('update:is-uploading', false);
                }
            } else {
                // 如果取消勾选或文件选择框不为空，则不显示示例文件
                this.$emit('update:exampleFileSelected', false);
                // if (isChecked) {

                //     ElMessage.warning('请先清空已选择的文件');

                // }
            }
        },
        async handleQuickQuestion(question) {
            this.query = question;


            if (this.files.length === 0) {
                this.$emit('update:exampleFileSelected', true);
                // 开始上传文件
                this.uploading = true;
                this.$emit('update:is-uploading', true);
                const response = await fetch('/商圈数据.csv');
                // const response = await fetch('/30种家庭常用解酒方法.txt');
                const blob = await response.blob();
                const file = new File([blob], '商圈数据.csv', {
                    // const file = new File([blob], '30种家庭常用解酒方法.txt》', {
                    type: 'application/pdf'
                });
                this.egfiles = [file];
                console.log(this.egfiles);
                const formData = new FormData();
                this.egfiles.forEach(file => {
                    formData.append('file', file);
                });
                try {
                    const response = await fetch(`${BASE_URL}/api/fuxigen-sessionid`, {
                        method: 'POST',
                        body: formData
                    });
                    if (response.ok) {
                        const res = await response.json();
                        this.$emit('update:resMsg', res.message);
                        this.$emit('update:id', res.id);
                        ElMessage.success('文件上传成功');
                    } else {
                        throw new Error('上传失败');
                    }
                } catch (error) {
                    console.error('上传文件时出错:', error);
                    ElMessage.error('上传文件失败，请重试');
                } finally {
                    this.uploading = false;
                    this.$emit('update:is-uploading', false);
                }
            }
        },
        handleClear() {
            this.query = '';
            this.$emit('update:exampleFileSelected', false);
        },

    },

}